<?php

namespace App\Console\Commands;

use App\Project;
use App\ProjectAttachment;
use App\Services\FileService;
use App\Services\WordToPdfService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use Log;

class SyncAttachments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync-attachments {project_ids?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->log('Command started');

        $fileSvc = new FileService();
        if (($sProjectIds = $this->argument('project_ids')) !== null) {
            $projectIds = explode(',', $sProjectIds);
            $projects = Project::whereIn('id', $projectIds)->get();
        } else {
            $projects = Project::whereNotIn('status_id', [Project::STATUS_FORMAL_REVIEW_FILL_APPLICATION, Project::STATUS_FORMAL_REVIEW_RETURNED_TO_FILL])
                ->where('attachment_processed', 0)
                ->get();
        }
        $this->log($projects->count() . ' projects to sync');
//        dd($projects->count());
        foreach ($projects as $project) {
            $this->log("Project #{$project->id}");
            $fileSvc->syncProjectAttachmentsFromFormData($project);
            $project->update(['attachment_processed' => 1]);
        }

        $this->log('Command finished');
    }

    private function log($msg)
    {
        $now = now();
        $pid = posix_getpid();
        $this->line("[$now][$pid]$msg");
    }
}
